package top.lyc829.zzl_android.ui.base_detail;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.gson.Gson;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.button.shinebutton.ShineButton;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xutil.data.DateUtils;
import com.youth.banner.indicator.RoundLinesIndicator;
import com.youth.banner.util.BannerUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.Response;
import top.lyc829.zzl_android.R;
import top.lyc829.zzl_android.databinding.ActivityBaseDetailBinding;
import top.lyc829.zzl_android.logic.bean.BaseDetailBean;
import top.lyc829.zzl_android.logic.bean.ResultBean;
import top.lyc829.zzl_android.logic.bean.ShareBean;
import top.lyc829.zzl_android.logic.bean.SonCommentBean;
import top.lyc829.zzl_android.logic.bean.SuperCommentBean;
import top.lyc829.zzl_android.logic.network.Network;
import top.lyc829.zzl_android.logic.util.DynamicType;
import top.lyc829.zzl_android.logic.util.FellowType;
import top.lyc829.zzl_android.logic.util.HttpUtil;
import top.lyc829.zzl_android.logic.util.PageInfo;
import top.lyc829.zzl_android.logic.util.ReplayType;
import top.lyc829.zzl_android.logic.util.RichUtils;
import top.lyc829.zzl_android.logic.util.Utils;
import top.lyc829.zzl_android.logic.util.gson.JsonUtilNew;
import top.lyc829.zzl_android.ui.base_detail.show_map.ShowMapActivity;
import top.lyc829.zzl_android.ui.custom_view.InputTextMsgDialog;
import top.lyc829.zzl_android.ui.custom_view.ShareMsgDialog;
import top.lyc829.zzl_android.ui.login.LoginActivity;
import top.lyc829.zzl_android.ui.profile.follow.user_detail.OtherUserDetailActivity;
import top.lyc829.zzl_android.ui.team.add_team.AddTeamActivity;
import top.lyc829.zzl_android.ui.team.team_detail.TeamDetailActivity;
import top.lyc829.zzl_android.ui.thing.travel_detail.TravelDetailActivity;

public class BaseDetailActivity extends AppCompatActivity {

    BaseDetailViewModel mViewModel;
    ActivityBaseDetailBinding binding;
    CommentsAdapter adapter;
    SonCommentsAdapter sonAdapter;
    int baseId;
    PageInfo pageInfo, sonPageInfo;
    BottomSheetDialog dialog;
    BottomSheetDialog deleteDialog;
    InputTextMsgDialog inputTextMsgDialog;
    ShareMsgDialog shareMsgDialog;
    MaterialDialog loadingDialog;

    int commentedUserId = -1;

    private int replayType = ReplayType.OTHER;
    private int commendedId = -1;    // 被评论的评论的id

    private boolean isNeedComment = false;

    MiniLoadingDialog mMiniLoadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityBaseDetailBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());


        // 实例化加载框
        loadingDialog = new MaterialDialog.Builder(this)
                .customView(R.layout.dialog_loading_layout, true)
                .cancelable(false)
                .build();

        mMiniLoadingDialog =  WidgetUtils.getMiniLoadingDialog(this);
        mMiniLoadingDialog.updateMessage("加载中");
        mMiniLoadingDialog.setCancelable(false);

        initTitleBar();
        initBanner();
        initCommentDialog();
        pageInfo = new PageInfo();
        sonPageInfo = new PageInfo();
        mViewModel = new ViewModelProvider(this).get(BaseDetailViewModel.class);
        baseId = getIntent().getIntExtra("id", -1);
        isNeedComment = getIntent().getBooleanExtra("is_comment", false);
        mViewModel.getBaseDetailFromServer(baseId);

        updateRecommendBases(baseId);
        mViewModel.getRecommendTravels(baseId, 1);
        mViewModel.getRecommendTeams(baseId, 1);

        initCommentAdapter();
        mViewModel.getSuperComments(baseId, pageInfo.getPage());

        initLoadMore();

        observe();

        clickListener();

    }

    private void observe() {

        mViewModel.getBaseDetailBeanMutableLiveData().observe(this, baseDetailBean -> {
            updateUI(baseDetailBean);
        });


        mViewModel.getTravelsSimplesLiveData().observe(this, travelsSimpleBeans -> {
            if (travelsSimpleBeans.size() >= 2) {
                binding.baseDetailRecommendTravel1.getRoot().setVisibility(View.VISIBLE);
                binding.baseDetailRecommendTravel1.travelsItemTitle.setText(travelsSimpleBeans.get(0).getTitle());
                Glide.with(this)
                        .load(RichUtils.returnImageUrlsFromHtml(travelsSimpleBeans.get(0).getText()).get(0))
                        .into(binding.baseDetailRecommendTravel1.travelsItemImg);
                binding.baseDetailRecommendTravel1.travelsItemDescribe.setText(RichUtils.returnOnlyText(travelsSimpleBeans.get(0).getText()));

                binding.baseDetailRecommendTravel2.getRoot().setVisibility(View.VISIBLE);
                binding.baseDetailRecommendTravel2.travelsItemTitle.setText(travelsSimpleBeans.get(1).getTitle());
                Glide.with(this)
                        .load(RichUtils.returnImageUrlsFromHtml(travelsSimpleBeans.get(1).getText()).get(0))
                        .into(binding.baseDetailRecommendTravel2.travelsItemImg);
                binding.baseDetailRecommendTravel2.travelsItemDescribe.setText(RichUtils.returnOnlyText(travelsSimpleBeans.get(1).getText()));
            } else if (travelsSimpleBeans.size() == 1) {
                binding.baseDetailRecommendTravel1.getRoot().setVisibility(View.VISIBLE);
                binding.baseDetailRecommendTravel1.travelsItemTitle.setText(travelsSimpleBeans.get(0).getTitle());
                Glide.with(this)
                        .load(RichUtils.returnImageUrlsFromHtml(travelsSimpleBeans.get(0).getText()).get(0))
                        .into(binding.baseDetailRecommendTravel1.travelsItemImg);
                binding.baseDetailRecommendTravel1.travelsItemDescribe.setText(RichUtils.returnOnlyText(travelsSimpleBeans.get(0).getText()));

                binding.baseDetailRecommendTravel2.getRoot().setVisibility(View.GONE);
            } else {
                binding.baseDetailRecommendTravel1.getRoot().setVisibility(View.GONE);
                binding.baseDetailRecommendTravel2.getRoot().setVisibility(View.GONE);
            }

        });

        mViewModel.getTeamSimplesLiveData().observe(this, teamSimpleBeans -> {

            if (teamSimpleBeans.size() >= 2) {
                binding.baseDetailRecommendTeam1.getRoot().setVisibility(View.VISIBLE);
                binding.baseDetailRecommendTeam1.travelsItemTitle.setText(teamSimpleBeans.get(0).getTitle());
                Glide.with(this)
                        .load(teamSimpleBeans.get(0).getImgUrl())
                        .into(binding.baseDetailRecommendTeam1.travelsItemImg);
                binding.baseDetailRecommendTeam1.travelsItemDescribe.setText(teamSimpleBeans.get(0).getDescribe());

                binding.baseDetailRecommendTeam2.getRoot().setVisibility(View.VISIBLE);
                binding.baseDetailRecommendTeam2.travelsItemTitle.setText(teamSimpleBeans.get(1).getTitle());
                Glide.with(this)
                        .load(teamSimpleBeans.get(1).getImgUrl())
                        .into(binding.baseDetailRecommendTeam2.travelsItemImg);
                binding.baseDetailRecommendTeam2.travelsItemDescribe.setText(teamSimpleBeans.get(1).getDescribe());
            } else if (teamSimpleBeans.size() == 1) {
                binding.baseDetailRecommendTeam1.getRoot().setVisibility(View.VISIBLE);
                binding.baseDetailRecommendTeam1.travelsItemTitle.setText(teamSimpleBeans.get(0).getTitle());
                Glide.with(this)
                        .load(teamSimpleBeans.get(0).getImgUrl())
                        .into(binding.baseDetailRecommendTeam1.travelsItemImg);
                binding.baseDetailRecommendTeam1.travelsItemDescribe.setText(teamSimpleBeans.get(0).getDescribe());

                binding.baseDetailRecommendTeam2.getRoot().setVisibility(View.GONE);
            } else {
                binding.baseDetailRecommendTeam1.getRoot().setVisibility(View.GONE);
                binding.baseDetailRecommendTeam2.getRoot().setVisibility(View.GONE);
            }


        });

        mViewModel.getSuperCommentsLiveData().observe(this, superCommentBeans -> {
            if (pageInfo.isFirstPage()) {
                adapter.setList(superCommentBeans);

                if (isNeedComment) {
                    scrollToEnd();
                    isNeedComment = false;
                }

            } else {
                adapter.addData(superCommentBeans);
            }

            if (superCommentBeans.size() < PageInfo.MAX_ITEM) {
                adapter.getLoadMoreModule().loadMoreEnd();
            } else {
                pageInfo.nextPage();
                // 加载完成，等待下一次加载
                adapter.getLoadMoreModule().loadMoreComplete();
            }
        });

        mViewModel.getSonCommentsLiveData().observe(this, sonCommentBeans -> {
            if (sonPageInfo.isFirstPage()) {
                sonAdapter.setList(sonCommentBeans);
            } else {
                sonAdapter.addData(sonCommentBeans);
            }

            if (sonCommentBeans.size() < PageInfo.MAX_ITEM) {
                sonAdapter.getLoadMoreModule().loadMoreEnd();
            } else {
                sonPageInfo.nextPage();
                // 加载完成，等待下一次加载
                sonAdapter.getLoadMoreModule().loadMoreComplete();
            }
        });

        mViewModel.getAttentionStateLiveData().observe(this, integer -> {
            if (integer.equals(0)) {
                binding.baseDetailFollow.setText("关注");
                binding.baseDetailFollow.setBackgroundResource(R.drawable.btn_un_attentioned);
            } else if (integer.equals(1)) {
                binding.baseDetailFollow.setText("已关注");
                binding.baseDetailFollow.setBackgroundResource(R.drawable.btn_attentioned);
            }
        });


        mViewModel.getMyTeamStateLiveData().observe(this, myTeamState -> {

            if (myTeamState == null) {
                binding.btnGoAddTeam.setVisibility(View.VISIBLE);
                binding.btnGoAddTeam.setBackgroundResource(R.drawable.ic_baseline_add_circle_24_red);
                return;
            }

            if (myTeamState.getApplyState().equals("3")) {
                binding.btnGoAddTeam.setVisibility(View.VISIBLE);
                binding.btnGoAddTeam.setBackgroundResource(R.drawable.ic_baseline_add_circle_24_red);
                return;
            }

            if (myTeamState.getTeamId() > 0) {
                binding.btnGoAddTeam.setVisibility(View.INVISIBLE);
            } else {
                binding.btnGoAddTeam.setVisibility(View.VISIBLE);
                binding.btnGoAddTeam.setBackgroundResource(R.drawable.ic_baseline_add_circle_24_red);
            }
        });

        // 一级评论被评论数量变化
        mViewModel.getSonCommentChangePositionLiveData().observe(this, integerIntegerPair -> {

            Utils.Sout( "pair---------" + integerIntegerPair.toString());

            if (integerIntegerPair == null || integerIntegerPair.first.equals(-1) || integerIntegerPair.second.equals(Integer.MIN_VALUE)) {
                return;
            }else {
                SuperCommentBean superComment = adapter.getItem(integerIntegerPair.first);
                superComment.setReplyNums(superComment.getReplyNums() + integerIntegerPair.second);
                adapter.setData(integerIntegerPair.first, superComment);
                adapter.notifyItemChanged(integerIntegerPair.first);
                mViewModel.getSonCommentChangePositionLiveData().setValue(new Pair<>(integerIntegerPair.first, Integer.MIN_VALUE));
            }

        });

    }

    private void scrollToEnd() {
        binding.nestedScrollView.post(() -> {
            binding.nestedScrollView.fullScroll(View.FOCUS_DOWN);//滚到底部
        });
    }


    private void clickListener() {

        binding.baseDetailLocation.setOnClickListener(v -> {
            Intent intent = new Intent(this, ShowMapActivity.class);
            if (mViewModel.getBaseDetailBeanMutableLiveData().getValue() != null) {
                intent.putExtra("lat", mViewModel.getBaseDetailBeanMutableLiveData().getValue().getLatitude());
                intent.putExtra("lng", mViewModel.getBaseDetailBeanMutableLiveData().getValue().getLongitude());
            }
            startActivity(intent);
        });

        // 添加待点击的子控件
        adapter.addChildClickViewIds(R.id.comment_item_like_btn, R.id.comment_item_go_replay, R.id.comment_item_avatar);
        adapter.setOnItemClickListener((adapter, view, position) -> {
            showCommentDialog();
            replayType = ReplayType.COMMENT;    // 回复评论
            commendedId = ((SuperCommentBean) adapter.getData().get(position)).getCommentId();
            commentedUserId = ((SuperCommentBean) adapter.getData().get(position)).getUseId();
        });
        adapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter1, @NonNull View view, int position) {
                if (view.getId() == R.id.comment_item_go_replay) {
                    // 弹出BottomSheetDialog, 显示评论评论的评论
                    mViewModel.getSonCommentChangePositionLiveData().setValue(new Pair<>(position, Integer.MIN_VALUE));

                    mViewModel.getSonComments(((SuperCommentBean) adapter.getData().get(position)).getCommentId(), sonPageInfo.getPage());
                    showBottomSheetListDialog((SuperCommentBean) adapter.getData().get(position));

                } else if (view.getId() == R.id.comment_item_like_btn) {
                    if (!Utils.isLogin()) {
                        Utils.showToast("请先登录");
                        return;
                    }

                    //ShineButton shineButton = (ShineButton) view;
                    View itemView = binding.commentRecyclerview.getLayoutManager().findViewByPosition(position);
                    itemView.findViewById(R.id.comment_item_like_btn).setClickable(false);

                    SuperCommentBean superComment = adapter.getItem(position);
                    //未点赞，点赞请求
                    if (superComment.getIsLike().equals(0)) {
                        Network.sendLike(Utils.getUserId(), ReplayType.COMMENT, adapter.getItem(position).getCommentId(), new HttpUtil.MyCallback() {
                            @Override
                            public void success(Response res) throws IOException {
                                String resStr = res.body().string();
                                ResultBean<String> resultBean = JsonUtilNew.fromJsonObject(resStr, String.class);
                                if (resultBean.getCode().equals(200)) {
                                    runOnUiThread(() -> {
                                        View itemView = binding.commentRecyclerview.getLayoutManager().findViewByPosition(position);
                                        itemView.findViewById(R.id.comment_item_like_btn).setClickable(true);
                                        adapter.getItem(position).setIsLike(1);
                                        adapter.getItem(position).setCommentLikes(adapter.getItem(position).getCommentLikes() + 1);
                                        adapter.notifyDataSetChanged();
                                    });
                                } else {
                                    failed(new IOException(resStr));
                                }
                            }

                            @Override
                            public void failed(IOException e) {
                                runOnUiThread(() -> {
                                    Utils.SoutErr(e.getMessage());
                                    View itemView = binding.commentRecyclerview.getLayoutManager().findViewByPosition(position);
                                    itemView.findViewById(R.id.comment_item_like_btn).setClickable(true);
                                });

                            }
                        });
                    } else {
                        Network.sendUnLike(Utils.getUserId(), ReplayType.COMMENT, adapter.getItem(position).getCommentId(), new HttpUtil.MyCallback() {
                            @Override
                            public void success(Response res) throws IOException {
                                String resStr = res.body().string();
                                ResultBean<String> resultBean = JsonUtilNew.fromJsonObject(resStr, String.class);
                                if (resultBean.getCode().equals(200)) {
                                    runOnUiThread(() -> {
                                        View itemView = binding.commentRecyclerview.getLayoutManager().findViewByPosition(position);
                                        itemView.findViewById(R.id.comment_item_like_btn).setClickable(true);
                                        adapter.getItem(position).setIsLike(0);
                                        adapter.getItem(position).setCommentLikes(adapter.getItem(position).getCommentLikes() - 1);
                                        adapter.notifyDataSetChanged();
                                    });
                                } else {
                                    failed(new IOException(resStr));
                                }
                            }

                            @Override
                            public void failed(IOException e) {
                                runOnUiThread(() -> {
                                    Utils.SoutErr(e.getMessage());
                                    View itemView = binding.commentRecyclerview.getLayoutManager().findViewByPosition(position);
                                    itemView.findViewById(R.id.comment_item_like_btn).setClickable(true);
                                });

                            }
                        });
                    }
                } else if (view.getId() == R.id.comment_item_avatar) {
                    Intent intent = new Intent(BaseDetailActivity.this, OtherUserDetailActivity.class);
                    intent.putExtra("id", adapter.getItem(position).getUseId());
                    startActivity(intent);
                }
            }
        });

        // 一级评论长按删除监听
        adapter.setOnItemLongClickListener((adapter1, view, position) -> {
            if (!Utils.isLogin()) {
                return false;
            }
            // 如果不是自己的评论，不做处理
            if (!adapter.getItem(position).getUseId().equals(Utils.getUserId())) {
                return false;
            }

            mViewModel.getCommentDeleteLiveData().setValue(new Pair<>(1, position));
            showBottomDialog();

            return false;
        });

        // 监听关注按钮
        binding.baseDetailFollow.setOnClickListener(v -> {
            if (!Utils.isLogin()) { // 保证用户登陆之后才能继续操作
                Utils.showToast("请先登录");
                Utils.goLogin(this);
            } else if (mViewModel.getAttentionStateLiveData().getValue() != null) {
                mMiniLoadingDialog.show();
                if(mViewModel.getAttentionStateLiveData().getValue().equals(0)) {
                    Network.attention(Utils.getUserId(), FellowType.BASE, baseId, new HttpUtil.MyCallback() {
                        @Override
                        public void success(Response res) throws IOException {
                            String resultStr = res.body().string();
                            ResultBean resultBean = new Gson().fromJson(resultStr, ResultBean.class);
                            if (resultBean.getCode().equals(200)) {

                                runOnUiThread(() -> {
                                    mMiniLoadingDialog.dismiss();
                                    mViewModel.getAttentionStateLiveData().setValue(1);
                                });
                            } else {
                                failed(new IOException());
                            }
                        }

                        @Override
                        public void failed(IOException e) {
                            runOnUiThread(() -> {
                                mMiniLoadingDialog.dismiss();
                                Utils.showToast("关注失败");
                            });

                        }
                    });

                } else if (mViewModel.getAttentionStateLiveData().getValue().equals(1)) {
                    Network.unAttention(Utils.getUserId(), ReplayType.BASE, baseId, new HttpUtil.MyCallback() {
                        @Override
                        public void success(Response res) throws IOException {
                            String resultStr = res.body().string();
                            ResultBean resultBean = new Gson().fromJson(resultStr, ResultBean.class);
                            if (resultBean.getCode().equals(200)) {
                                runOnUiThread(() -> {
                                    mMiniLoadingDialog.dismiss();
                                    mViewModel.getAttentionStateLiveData().setValue(0);
                                });
                            } else {
                                failed(new IOException());
                            }
                        }

                        @Override
                        public void failed(IOException e) {
                            runOnUiThread(() -> {
                                mMiniLoadingDialog.dismiss();
                                Utils.showToast("取消关注失败");
                            });
                        }
                    });

                }
            }


        });



        binding.baseBottomComment.setOnClickListener(v -> {
            showCommentDialog();
            replayType = ReplayType.BASE;
            commendedId = baseId;
        });

        binding.recommendBase1.setOnClickListener(v -> {
            Intent intent = new Intent(this, BaseDetailActivity.class);
            intent.putExtra("id", mViewModel.getRecommendBeansLiveData().getValue().get(0).getId());
            startActivity(intent);
        });
        binding.recommendBase2.setOnClickListener(v -> {
            Intent intent = new Intent(this, BaseDetailActivity.class);
            intent.putExtra("id", mViewModel.getRecommendBeansLiveData().getValue().get(1).getId());
            startActivity(intent);
        });


        binding.btRefresh.setOnClickListener(v -> {
            mViewModel.getRecommendBases(baseId);
        });


        binding.baseDetailRecommendTeam1.getRoot().setOnClickListener(v -> {
            int id = mViewModel.getTeamSimplesLiveData().getValue().get(0).getId();
            Intent intent = new Intent(BaseDetailActivity.this, TeamDetailActivity.class);
            intent.putExtra("team_id", id);
            startActivity(intent);
        });
        binding.baseDetailRecommendTeam2.getRoot().setOnClickListener(v -> {
            int id = mViewModel.getTeamSimplesLiveData().getValue().get(1).getId();
            Intent intent = new Intent(BaseDetailActivity.this, TeamDetailActivity.class);
            intent.putExtra("team_id", id);
            startActivity(intent);
        });

        binding.baseDetailRecommendTravel1.getRoot().setOnClickListener(v -> {
            int id = mViewModel.getTravelsSimplesLiveData().getValue().get(0).getId();
            Intent intent = new Intent(BaseDetailActivity.this, TravelDetailActivity.class);
            intent.putExtra("travel_id", id);
            startActivity(intent);
        });
        binding.baseDetailRecommendTravel2.getRoot().setOnClickListener(v -> {
            int id = mViewModel.getTravelsSimplesLiveData().getValue().get(1).getId();
            Intent intent = new Intent(BaseDetailActivity.this, TravelDetailActivity.class);
            intent.putExtra("travel_id", id);
            startActivity(intent);
        });

        binding.btnGoAddTeam.setOnClickListener(v -> {
            if (!Utils.isLogin()) {
                Utils.showToast("请先登录");
            }
            Intent intent = new Intent(this, AddTeamActivity.class);
            startActivity(intent);
        });

    }

    /**
     * 弹出底部删除弹窗
     */
    private void showBottomDialog() {
        if (deleteDialog == null) {
            deleteDialog = new BottomSheetDialog(this, R.style.MyBottomSheetDialog);
            View view = LayoutInflater.from(this).inflate(R.layout.bottom_sheet_dialog_dynamic_long_click, null);

            view.findViewById(R.id.dynamic_long_delete).setOnClickListener(v -> {
                deleteComment();
                deleteDialog.dismiss();
            });

            view.findViewById(R.id.dynamic_long_cancel).setOnClickListener(v -> {
                deleteDialog.dismiss();
            });

            deleteDialog.setContentView(view);
            deleteDialog.setCancelable(true);
            deleteDialog.setCanceledOnTouchOutside(true);
        }
        deleteDialog.show();

    }

    /**
     * 删除评论
     */
    private void deleteComment() {
        if (mViewModel.getCommentDeleteLiveData().getValue() == null) {
            return;
        }
        Pair<Integer, Integer> commentPair = mViewModel.getCommentDeleteLiveData().getValue();

        int commentId = -1;
        if (commentPair.first.equals(1)) {
            commentId = adapter.getItem(commentPair.second).getCommentId();
        } else {
            commentId = sonAdapter.getItem(commentPair.second).getCommentId();
        }
        Network.deleteComment(Utils.getUserId(), commentId, new HttpUtil.MyCallback() {
            @Override
            public void success(Response res) throws IOException {
                String resStr = res.body().string();
                ResultBean<String> resultBean = JsonUtilNew.fromJsonObject(resStr, String.class);
                if (resultBean.getCode().equals(200)) {
                    runOnUiThread(() -> {
                        Utils.showToast("删除成功");
                        if (commentPair.first.equals(1)) {
                            adapter.removeAt(commentPair.second);
                        } else {
                            sonAdapter.removeAt(commentPair.second);

                            if (mViewModel.getSonCommentChangePositionLiveData().getValue() != null) {
                                Pair<Integer, Integer> value = new Pair<>(mViewModel.getSonCommentChangePositionLiveData().getValue().first, -1);
                                mViewModel.getSonCommentChangePositionLiveData().postValue(value);
                            }



                        }
                    });
                } else {
                    failed(new IOException(resultBean.getMsg()));
                }
            }

            @Override
            public void failed(IOException e) {
                Utils.Sout(e.getMessage());
            }
        });
    }

    /**
     * 弹出底部评论弹窗
     */
    private void showCommentDialog() {

        if (!Utils.isLogin()) {
            Utils.showToast("请先登录");
            //Intent intent = new Intent(BaseDetailActivity.this, LoginActivity.class);
            //startActivity(intent);
            return;
        } else {
            inputTextMsgDialog.show();
        }
    }

    /**
     * 初始化底部评论弹窗
     */
    private void initCommentDialog() {
        if(inputTextMsgDialog == null) {
            inputTextMsgDialog = new InputTextMsgDialog(this, R.style.dialog_center);
            inputTextMsgDialog.setmOnTextSendListener(new InputTextMsgDialog.OnTextSendListener() {
                @Override
                public void onTextSend(String msg) {
                    inputTextMsgDialog.dismiss();

                    loadingDialog.show();

                    Network.sendComments(Utils.getUserId(),
                            replayType, commendedId, msg, commentedUserId, new HttpUtil.MyCallback() {
                        @Override
                        public void success(Response res) throws IOException {
                            String resultStr = res.body().string();
                            ResultBean resultBean = new Gson().fromJson(resultStr, ResultBean.class);
                            if (resultBean.getCode().equals(200)) {
                                loadingDialog.dismiss();

                                // 子评论界面没有加载，则刷新一级评论，否则刷新N级评论
                                if (dialog == null || !dialog.isShowing()) {
                                    pageInfo.reset();
                                    // 重新获取以及评论
                                    mViewModel.getSuperComments(baseId, pageInfo.getPage());
                                } else {
                                    sonPageInfo.reset();
                                    // 重新获取子评论
                                    mViewModel.getSonComments(commendedId, sonPageInfo.getPage());

                                    if (mViewModel.getSonCommentChangePositionLiveData().getValue() != null) {
                                        Pair<Integer, Integer> value = new Pair<>(mViewModel.getSonCommentChangePositionLiveData().getValue().first, 1);
                                        mViewModel.getSonCommentChangePositionLiveData().postValue(value);
                                    }

                                }


                            } else {
                                failed(new IOException());
                            }

                        }

                        @Override
                        public void failed(IOException e) {
                            loadingDialog.dismiss();
                            Utils.showToastSync("评论失败");
                        }
                    });


                }
            });
        }
    }

    /**
     * 在底部弹出评论的评论
     */
    private void showBottomSheetListDialog(SuperCommentBean superComment) {

        dialog = new BottomSheetDialog(this);
        View view = LayoutInflater.from(this).inflate(R.layout.replay_comments, null);
        RecyclerView recyclerView = view.findViewById(R.id.replay_recyclerview);

        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(RecyclerView.VERTICAL);
        recyclerView.setLayoutManager(manager);
        sonAdapter = new SonCommentsAdapter();
        recyclerView.setAdapter(sonAdapter);
        sonAdapter.setList(null);

        dialog.setContentView(view);
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();

        ((TextView) view.findViewById(R.id.replay_nums)).setText("回复");
        // 点击箭头关闭BottomSheetDialog
        ((ImageButton) view.findViewById(R.id.replay_back_btn)).setOnClickListener(v -> dialog.cancel());

        ((TextView) view.findViewById(R.id.comment_item_username)).setText(superComment.getUserName());
        ((TextView) view.findViewById(R.id.comment_item_time)).setText(DateUtils.millis2String(Long.parseLong(superComment.getCommentTime()), DateUtils.yyyyMMdd.get()));
        ((TextView) view.findViewById(R.id.comment_item_text)).setText(superComment.getCommentText());
        ((TextView) view.findViewById(R.id.comment_item_go_replay)).setVisibility(View.GONE);
        //((TextView) view.findViewById(R.id.comment_item_like_nums)).setText(String.valueOf(superComment.getCommentLikes()));
        ((TextView) view.findViewById(R.id.comment_item_like_nums)).setVisibility(View.INVISIBLE);
        view.findViewById(R.id.comment_item_like_btn).setVisibility(View.INVISIBLE);

        Glide.with(this)
                .load(superComment.getImgUrl())
                .into((ImageView)view.findViewById(R.id.comment_item_avatar));

        // 点击子评论的评论框弹出评论框, 评论父评论
        view.findViewById(R.id.replay_bottom_comment).setOnClickListener(v -> {
            showCommentDialog();
            replayType = ReplayType.COMMENT;
            commendedId = superComment.getCommentId();
            commentedUserId = superComment.getUseId();
        });

        // 上拉加载
        initSonLoadMore(superComment.getCommentId());

        // 点击子评论进行评论
        sonAdapter.setOnItemClickListener((adapter1, view1, position) -> {

            Utils.Sout("子项点击");

            showCommentDialog();
            replayType = ReplayType.COMMENT;
            commendedId = superComment.getCommentId();
            commentedUserId = sonAdapter.getData().get(position).getUseId();
        });

        sonAdapter.addChildClickViewIds(R.id.replay_item_like_btn, R.id.replay_item_avatar);
        sonAdapter.setOnItemChildClickListener((adapter1, view1, position) -> {
            if (view1.getId() == R.id.replay_item_like_btn) {
                // 子评论点赞
                if (!Utils.isLogin()) {
                    Utils.showToast("请先登录");
                    return;
                }

                View itemView = recyclerView.getLayoutManager().findViewByPosition(position);
                itemView.findViewById(R.id.replay_item_like_btn).setClickable(false);
                //ShineButton shineButton = (ShineButton) view;
                SonCommentBean sonComment = sonAdapter.getItem(position);
                //未点赞，点赞请求
                if (sonComment.getIsLike().equals(0)) {
                    Network.sendLike(Utils.getUserId(), ReplayType.COMMENT, sonAdapter.getItem(position).getCommentId(), new HttpUtil.MyCallback() {
                        @Override
                        public void success(Response res) throws IOException {
                            String resStr = res.body().string();
                            ResultBean<String> resultBean = JsonUtilNew.fromJsonObject(resStr, String.class);
                            if (resultBean.getCode().equals(200)) {
                                runOnUiThread(() -> {
                                    View itemView = recyclerView.getLayoutManager().findViewByPosition(position);
                                    itemView.findViewById(R.id.replay_item_like_btn).setClickable(true);
                                    sonAdapter.getItem(position).setIsLike(1);
                                    sonAdapter.getItem(position).setCommentLikes(sonAdapter.getItem(position).getCommentLikes() + 1);
                                    sonAdapter.notifyDataSetChanged();
                                });
                            } else {
                                failed(new IOException(resStr));
                            }
                        }

                        @Override
                        public void failed(IOException e) {
                            runOnUiThread(() -> {
                                Utils.SoutErr(e.getMessage());
                                View itemView = recyclerView.getLayoutManager().findViewByPosition(position);
                                itemView.findViewById(R.id.replay_item_like_btn).setClickable(true);
                            });

                        }
                    });
                } else {
                    Network.sendUnLike(Utils.getUserId(), ReplayType.COMMENT, sonAdapter.getItem(position).getCommentId(), new HttpUtil.MyCallback() {
                        @Override
                        public void success(Response res) throws IOException {
                            String resStr = res.body().string();
                            ResultBean<String> resultBean = JsonUtilNew.fromJsonObject(resStr, String.class);
                            if (resultBean.getCode().equals(200)) {
                                runOnUiThread(() -> {
                                    View itemView = recyclerView.getLayoutManager().findViewByPosition(position);
                                    itemView.findViewById(R.id.replay_item_like_btn).setClickable(true);
                                    sonAdapter.getItem(position).setIsLike(0);
                                    sonAdapter.getItem(position).setCommentLikes(sonAdapter.getItem(position).getCommentLikes() - 1);
                                    sonAdapter.notifyDataSetChanged();
                                });
                            } else {
                                failed(new IOException(resStr));
                            }
                        }

                        @Override
                        public void failed(IOException e) {
                            runOnUiThread(() -> {
                                Utils.SoutErr(e.getMessage());
                                View itemView = recyclerView.getLayoutManager().findViewByPosition(position);
                                itemView.findViewById(R.id.replay_item_like_btn).setClickable(true);
                            });

                        }
                    });
                }
            } else if (view1.getId() == R.id.replay_item_avatar) {
                Intent intent = new Intent(BaseDetailActivity.this, OtherUserDetailActivity.class);
                intent.putExtra("id", sonAdapter.getItem(position).getUseId());
                startActivity(intent);
            }
        });


        // 子评论长按删除
        sonAdapter.setOnItemLongClickListener((adapter1, view1, position) -> {
            if (!Utils.isLogin()) {
                return false;
            }
            // 如果不是自己的评论，不做处理
            if (!sonAdapter.getItem(position).getUseId().equals(Utils.getUserId())) {
                return false;
            }

            mViewModel.getCommentDeleteLiveData().setValue(new Pair<>(2, position));
            showBottomDialog();

            return false;
        });

    }

    /**
     * 上拉加载更多评论
     */
    private void initLoadMore() {
        adapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                request();
            }
        });
        adapter.getLoadMoreModule().setAutoLoadMore(true);
        //当自动加载开启，同时数据不满一屏时，是否继续执行自动加载更多(默认为true)
        adapter.getLoadMoreModule().setEnableLoadMoreIfNotFullPage(false);
    }

    /**
     * 子评论上拉加载更多
     */
    private void initSonLoadMore(int superId) {
        sonAdapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                sonRequest(superId);
            }
        });
        sonAdapter.getLoadMoreModule().setAutoLoadMore(true);
        //当自动加载开启，同时数据不满一屏时，是否继续执行自动加载更多(默认为true)
        sonAdapter.getLoadMoreModule().setEnableLoadMoreIfNotFullPage(false);
    }

    private void sonRequest(int superId) {
        mViewModel.getSonComments(superId, sonPageInfo.getPage());
    }


    private void request() {
        mViewModel.getSuperComments(baseId, pageInfo.getPage());
    }

    private void initCommentAdapter() {
        adapter = new CommentsAdapter();
        adapter.setAnimationEnable(true);
        binding.commentRecyclerview.setLayoutManager(new LinearLayoutManager(this));
        binding.commentRecyclerview.setAdapter(adapter);
        adapter.setList(null);
    }

    /**
     * 根据基地id获取推荐基地，并展示在界面上。
     * @param baseId 当前基地id
     */
    private void updateRecommendBases(int baseId) {
        mViewModel.getRecommendBases(baseId);

        mViewModel.getRecommendBeansLiveData().observe(this, baseBeans -> {
            Utils.Sout(baseBeans.toString());
            binding.recommendBaseTitle1.setText(baseBeans.get(0).getTitle());
            binding.recommendBaseTitle2.setText(baseBeans.get(1).getTitle());

            Glide.with(this)
                    .load(baseBeans.get(0).getIndexImgUrl())
                    .into(binding.recommendBaseImg1);
            Glide.with(this)
                    .load(baseBeans.get(1).getIndexImgUrl())
                    .into(binding.recommendBaseImg2);

        });
    }

    /**
     * 收到数据后更新UI
     * @param baseDetailBean 基地详细信息实体
     */
    private void updateUI(BaseDetailBean baseDetailBean) {
        List<String> banners = new ArrayList<>();
        for (String url : baseDetailBean.getBannerImageUrls()) {
            if (!Utils.isStringEmpty(url)) {
                banners.add(url);
            }
        }
        binding.bannerBaseDetail.setAdapter(new BaseDetailBannerAdapter(banners));
        binding.baseDetailTitle.setText(baseDetailBean.getTitle());
        binding.baseDetailLocation.setText(baseDetailBean.getAddress());
        binding.baseDetailDescribe.setText(baseDetailBean.getDescribe());
    }

    private void initBanner() {
        binding.bannerBaseDetail.setDelayTime(5000);
        binding.bannerBaseDetail.setIndicator(new RoundLinesIndicator(this));
        binding.bannerBaseDetail.setIndicatorSelectedWidth((int) BannerUtils.dp2px(15));
    }


    private void initTitleBar() {
        binding.mTitleBarBaseDetail.setLeftClickListener(v -> finish());
        binding.mTitleBarBaseDetail.addAction(new TitleBar.ImageAction(R.drawable.ic_baseline_share_24) {
            @Override
            public void performAction(View view) {
                if (!Utils.isLogin()) {
                    Utils.showToast("请先登录");
                    return;
                }

                if (shareMsgDialog == null) {

                    BaseDetailBean baseDetail = mViewModel.getBaseDetailBeanMutableLiveData().getValue();

                    shareMsgDialog = new ShareMsgDialog(
                            BaseDetailActivity.this,
                            R.style.dialog_center,
                            new ShareBean(baseDetail.getTitle(), baseDetail.getDescribe(), baseDetail.getBannerImageUrls().get(0)));
                    shareMsgDialog.setmOnTextSendListener(msg -> {
                        shareMsgDialog.dismiss();
                        loadingDialog.show();

                        Network.shareToDynamic(DynamicType.BASE, baseDetail.getId(), Utils.getUserId(), msg, new HttpUtil.MyCallback() {
                            @Override
                            public void success(Response res) throws IOException {
                                String resStr = res.body().string();
                                ResultBean<String> resultBean = JsonUtilNew.fromJsonObject(resStr, String.class);
                                if (resultBean.getCode().equals(200)) {
                                    runOnUiThread(() ->{
                                        loadingDialog.dismiss();
                                        Utils.showToast("分享成功");
                                    });
                                } else {
                                    failed(new IOException(resultBean.getMsg()));
                                }
                            }

                            @Override
                            public void failed(IOException e) {
                                runOnUiThread(() -> {
                                    Utils.Sout(e.getMessage());
                                    loadingDialog.dismiss();
                                });

                            }
                        });

                    });

                }

                shareMsgDialog.show();


            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        mViewModel.getMyTeamIdFromServer(Utils.getUserId());
        // 获取关注关系在onResume中，因为用户可能重登录页返回该页面
        if (Utils.isLogin()) {
            mViewModel.getAttentionState(Utils.getUserId(), ReplayType.BASE, baseId);
        }
    }

    @Override
    protected void onDestroy() {

        inputTextMsgDialog.cancel();
        inputTextMsgDialog = null;
        if (loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
        loadingDialog = null;

        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        dialog = null;

        if (shareMsgDialog != null && shareMsgDialog.isShowing()) {
            shareMsgDialog.dismiss();
        }
        shareMsgDialog = null;

        if (deleteDialog != null && deleteDialog.isShowing()) {
            deleteDialog.dismiss();
        }
        deleteDialog = null;


        super.onDestroy();

    }
}